package com.github.admin.edu.security.jwt.client.interceptor;

import com.fasterxml.jackson.core.type.TypeReference;
import com.github.admin.edu.assembly.common.entity.JsonEntity;
import com.github.admin.edu.assembly.common.util.JsonUtils;
import com.github.admin.edu.assembly.string.util.StringUtils;
import com.github.admin.edu.oauth.server.api.entity.TokenEntity;
import com.github.admin.edu.security.jwt.client.Service.ClientHeaderTokenService;
import com.github.admin.edu.security.jwt.client.domain.ServiceClientAuthDomain;
import feign.Request;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

/**
 * Create by IntelliJ IDEA
 * 用户：王建
 * 日期：2018-7-20
 */
public class FeignClientResultInterceptor implements RequestInterceptor {

    private static final Logger log = LoggerFactory.getLogger(FeignClientResultInterceptor.class);

    @Autowired
    private ClientHeaderTokenService service;

    @Value("${server.custom.server.server-id}")
    private String serverId;

    @Value("${server.custom.token.header.token-header}")
    private String tokenHeader;

    @Value("${server.custom.token.header.client-id}")
    private String clientId;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        try {
            Request request = requestTemplate.request();
            String url = request.url();
            if (StringUtils.isNotBlank(url)) {
                if (url.indexOf("/rest/api/oauth/token") == -1 && url.indexOf("/rest/api/oauth/authentication") == -1) {
                    String code = service.getToken();
                    if (StringUtils.isNotBlank(code)) {
                        requestTemplate.header(tokenHeader, code);
                        requestTemplate.header(clientId, serverId);
                    }
                }
            }
        } catch (Exception e) {
            log.error(" 设置请求头信息失败！：" + e.getMessage());
        }
    }
}
